const fs = require("fs")

const path = require("path")

const mongoose = require("mongoose")

function load(dir, cb) {
  //获取绝对路径
  const url = path.resolve(__dirname, dir)
  const files = fs.readdirSync(url)
  files.forEach(fileName => {
    //去后缀
    fileName = fileName.replace(".js", "")

    //导入文件
    const file = require(url + "/" + fileName)

    //处理
    cb(fileName, file)
  })
}

const loadModel = config => app => {
  mongoose.connect(config.url, config.options)
  const conn = mongoose.connection
  conn.on("error", () => console.error("数据库连接出错"))
  app.$model = {}
  load("../model", (fileName, { schema }) => {
    console.log("load model:" + fileName, schema)
    app.$model[fileName] = mongoose.model(fileName, schema)
  })
}

module.exports = {
  loadModel
}
